/**
 * show 系统后台全文检索配置服务JS-fulltextSearchService.jsp
 * by date 2018/03/12 guoyanfei
 */

var searchService = function(){
    //项目路径
    var strPath = window.document.location.pathname;
    //var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
    var postPath = "/gdp";
    var tablelist =[];//检索库表信息集合

    //基础设置
    var otherOption = function () {
        //初始化滚动条
        $(".scroller").slimScroll({
            height: '120px'
        });
        $(".scrollertwo").slimScroll({
            height:'220px'
        });
        $(".scrollerthree").slimScroll({
            height:'300px'
        });

        //返回上级目录
        $("#btn_back").click(function(){
            window.location.href=postPath + "/prjService/index";
        });

        //修改操作初始化数据
        if($("#hid_operate").val() == "edit"){
            //加载全文检索基本信息
            $.ajax({
                url:postPath+'/system/fullTextSearch/selectCfgExtsearch',
                type:'post',
                data:{guid:$("#hid_serviceId").val()},
                async:false,
                success:function (res) {
                    if(res != null){
                        $("#guid").val(res.guid);
                        $("#servicename").val(res.servicename);
                        $("#remark").val(res.remark);
                        $("#cronexpression").val(res.cronexpression);
                        $("#guid").attr("readonly","readonly");
                        switch (res.status){
                            case 0:
                                $("#lab_status").html("关闭");
                                break;
                            case 1:
                                $("#lab_status").html("正常");
                                break;
                            case 2:
                                $("#lab_status").html("正在更新索引库");
                                break;
                        }
                    }
                }
            });

            //加载全文检索配置信息
            $.ajax({
                url:postPath+'/system/fullTextSearch/selectFullsearch',
                type:'post',
                data:{guid:$("#hid_serviceId").val()},
                async:false,
                success:function (res) {
                    $.each(res,function (i,e) {
                        var tab = {
                            "guid":e.guid,
                            "dbkey":e.dbkey,
                            "dbtext":e.dbtext,
                            "dtConfigid":e.dtConfigid,
                            "dtConfigtext":e.dtConfigtext,
                            "fieldid":e.fieldid,
                            "fieldtext":e.fieldtext,
                            "updatetype":e.updatetype,
                            "updatefield":e.updatefield,
                            "updatefieldtext":e.updatefieldtext,
                            "updatevalue":e.updatevalue
                        };
                        tablelist.push(tab);
                    });

                    searchTable.addtableEvent();
                }
            });
        }
    };

    //检索库表维护
    var searchTable ={
        showModul:function(){
            //显示Modul-新增检索库表
            $("#btna_add").click(function(){
                $("#dtConfigid").select2("val", "");
                $("#showColumns").html("");
                $("#updatetype").val("0");
                $("#updatefield").val("");
                $("#updatevalue").val("");
                $("#div_field").css("display","none");
                $("#dataTableModul").modal("show");
            });
        },
        dataload:function(){
            //初始化select2控件
            //1、查询所有配置的数据库
            $.ajax({
                url:postPath+'/system/fullTextSearch/getAlldatabase',
                type:'POST',
                success:function (data) {
                    $("#dbkey").html('');
                    $("#dbkey").append('<option value="">请选择库</option>');
                    $.each(data,function (i,e) {
                        $("#dbkey").append('<option value="'+e.dbKey+'">'+e.dbMark+'('+e.dbName+')'+'</option>');
                    });
                }

            });
            $("#dbkey").select2();

            //2、通过dbkey查询表信息
            $("#dbkey").click(function () {
                $.ajax({
                    url:postPath+'/system/fullTextSearch/getTablesBydbkey',
                    type:'POST',
                    data:{dbkey:$("#dbkey").val()},
                    async:false,
                    success:function (data) {
                        $("#dtConfigid").html('');
                        $("#dtConfigid").append('<option value="">请选择表</option>');
                        $.each(data,function (i,e) {
                           $("#dtConfigid").append('<option value="'+e.dtConfigId+'">'+e.dtNameCn+'('+e.dtName+')'+'</option>');
                        });
                    }
                });
            });
            $("#dtConfigid").select2();

            //3、通过表信息查询检索字段信息
            $("#dtConfigid").click(function () {
                searchField.getField($("#dbkey").val(),$("#dtConfigid").val());
                searchField.getAllField($("#dtConfigid").val());
            });

            //4、更新类型改变事件
            $("#updatetype").click(function () {
               if($(this).val() == "0"){
                   $("#div_field").css("display","none");
                   $("#updatefield").val("");
                   $("#updatevalue").val("");
               }else if($(this).val() == "1"){
                   $("#div_field").css("display","block");
               }
            });

        },
        savetableEvent:function () {
            //保存选择的检索库表信息
            $("#btn_modulsave").click(function () {
                //验证选择数据库
                if($("#dbkey").val() == ""){
                    $("#modulerror").html("请选择数据库!");
                    return;
                }else{
                    $("#modulerror").html("");
                }
                //验证选择数据表
                if($("#dtConfigid").val() == ""){
                    $("#modulerror").html("请选择数据表!");
                    return;
                }else {
                    $("#modulerror").html("");
                }
                //验证选择字段
                var strfieldid="";
                var strfieldCn="";
                $('input[name="showfile"]:checked').each(function(){
                    if(strfieldid == ""){
                        strfieldid +=$(this).val();
                    }else {
                        strfieldid +=","+$(this).val();
                    }
                    if(strfieldCn == ""){
                        strfieldCn +=$(this).attr("fieldcn");
                    }else {
                        strfieldCn +=","+$(this).attr("fieldcn");
                    }

                });
                if(strfieldid == ""){
                    $("#modulerror").html("请选择字段!");
                    return;
                }else{
                    $("#modulerror").html("");
                }

                //验证增量更新
                if($("#updatetype").val() == "1"){
                    if($("#updatefield").val() == ""){
                        $("#modulerror").html("请选择更新字段!");
                        return;
                    }else{
                        $("#modulerror").html("");
                    }
                }

                var dbkey = $("#dbkey").val();
                var dbtext = $("#dbkey").find("option:selected").text();
                var dtConfigid = $("#dtConfigid").val();
                var dtConfigtext = $("#dtConfigid").find("option:selected").text();
                var updatetype = $("#updatetype").val();
                var updatefield = $("#updatefield").val();
                var updatefieldtext = "";
                if(updatefield != ""){
                    updatefieldtext = $("#updatefield").find("option:selected").text();
                }
                var updatevalue = $("#updatevalue").val();
                var uuid = searchField.getuuid();

                var tab = {"guid":uuid,"dbkey":dbkey,"dbtext":dbtext,"dtConfigid":dtConfigid,"dtConfigtext":dtConfigtext,
                          "fieldid":strfieldid,"fieldtext":strfieldCn,"updatetype":updatetype,
                          "updatefield":updatefield,"updatefieldtext":updatefieldtext,"updatevalue":updatevalue};
                //去重复
                $.each(tablelist,function (i,e) {
                    if(e.dbkey ==dbkey && e.dtConfigid == dtConfigid){
                        tablelist.splice(e,1);
                    }
                });
                tablelist.push(tab);
                searchTable.addtableEvent();

                $("#dataTableModul").modal("hide");

            });
        },
        addtableEvent:function () {
            //构建表格
            $("#tb_datalist").bootstrapTable('destroy').bootstrapTable({
                data:tablelist,
                striped : true, // 是否显示行间隔色
                cache : false, // 是否使用缓存
                singleSelect:true,//单选
                uniqueId : "guid", // 每一行的唯一标识
                columns:[{
                    field : 'state',
                    checkbox : true,
                    align : 'center',
                    valign : 'middle'
                },{
                    title : '数据库',
                    field : 'dbtext',
                    align : 'center',
                    valign : 'middle'
                },{
                    title : '数据表',
                    field : 'dtConfigtext',
                    align : 'center',
                    valign : 'middle'
                },{
                    title : '字段集合',
                    field : 'fieldtext',
                    align : 'center',
                    valign : 'middle'
                },{
                    title : '更新类型',
                    field : 'updatetype',
                    align : 'center',
                    valign : 'middle',
                    formatter:function (value, row, index) {
                        if(value == "0"){
                            return "全部更新";
                        }else if(value == "1"){
                            return "增量更新";
                        }
                    }
                },{
                    title : '更新字段',
                    field : 'updatefieldtext',
                    align : 'center',
                    valign : 'middle'
                }]
            });

        },
        deltableEvent:function(){
            $("#btna_del").click(function () {
                var row = $('#tb_datalist').bootstrapTable('getSelections');
                if(row == null || row == ""){
                    bootbox.alert("请选择一行!");
                }else{
                    //移除检索库表集合
                    for (var i=0;i<tablelist.length;i++){
                        if(tablelist[i].guid == row[0].guid){
                            tablelist.splice(i,1);
                        }
                    }

                    //刷新表格信息
                    searchTable.addtableEvent();

                }

            });
        },
        updatetableEvent:function () {
            //修改表信息
            $("#btna_edit").click(function () {
                var row = $('#tb_datalist').bootstrapTable('getSelections');
                if(row == null || row == ""){
                    bootbox.alert("请选择一行!");
                    return;
                }
                //赋值修改信息
                //1、数据库赋值
                $("#dbkey").val(row[0].dbkey).trigger("change");
                //2、通过dbkey查询数据库表
                $.ajax({
                    url:postPath+'/system/fullTextSearch/getTablesBydbkey',
                    type:'POST',
                    data:{dbkey:$("#dbkey").val()},
                    async:false,
                    success:function (data) {
                        $("#dtConfigid").html('');
                        $("#dtConfigid").append('<option value="">请选择表</option>');
                        $.each(data,function (i,e) {
                            $("#dtConfigid").append('<option value="'+e.dtConfigId+'">'+e.dtNameCn+'('+e.dtName+')'+'</option>');
                        });
                    }
                });
                //3、数据表赋值
                $("#dtConfigid").val(row[0].dtConfigid).trigger("change");
                //4、通过dtConfigid查询字段信息
                searchField.getField($("#dbkey").val(),$("#dtConfigid").val());
                searchField.getAllField($("#dtConfigid").val());
                //5、字段信息赋值
                var strfield = row[0].fieldid;
                var fieldArray = strfield.split(",");
                for(var i=0;i<fieldArray.length;i++){
                    $('input[name="showfile"]').each(function(){
                        if($(this).val() == fieldArray[i]){
                            $(this).attr("checked","checked");
                        }
                    });
                }
                //6、更新类型赋值
                $("#updatetype").val(row[0].updatetype);
                if(row[0].updatetype == "1"){
                    //增量更新
                    $("#div_field").css("display","block");
                    $("#updatefield").val(row[0].updatefield);
                }else{
                    //全部更新
                    $("#div_field").css("display","none");
                    $("#updatefield").val("");
                }

                $("#dataTableModul").modal("show");

            });
        },
        init:function () {
            //初始化
            searchTable.showModul();
            searchTable.dataload();
            searchTable.savetableEvent();
            searchTable.deltableEvent();
            searchTable.updatetableEvent();
        }
    };

    //检索字段维护
    var searchField = {
        getField:function(dbkey,dtconfigid){
            //通过选择检索库表加载字段信息
            $.ajax({
                url:postPath+'/system/fullTextSearch/getFieldInfo',
                type:'post',
                data:{dtConfigId:dtconfigid},
                async:false,
                success:function (data) {
                    $("#showColumns").html("");
                    $.each(data,function (i,e) {
                        var fieldInfo = '<div class="md-checkbox">'
                                      + '<input id="show_'+e.dfName+'" dbk="'+dbkey+'" dbt="'+dtconfigid+'" fieldcn="'+e.dfNameCn+'" type="checkbox" name="showfile" value="'+e.guid+'" class="md-check">'
                                      + '<label for="show_'+e.dfName+'"><span></span><span class="check"></span><span class="box"></span> '+e.dfNameCn+' </label>'
                                      + '</div>';
                        $("#showColumns").append(fieldInfo);
                    });
                }
            });

        },
        getAllField:function (dtconfigid) {
            //查询所有字段
            $.ajax({
                url:postPath+'/system/fullTextSearch/getAllField',
                type:'post',
                data:{dtconfigid:dtconfigid},
                async:false,
                success:function (res) {
                    $("#updatefield").html("");
                    $("#updatefield").append("<option value=''>请选择</option>");
                    $.each(res,function (i,e) {
                        $("#updatefield").append("<option value='"+e.guid+"'>"+e.dfNameCn+"</option>");
                    });
                }
            });
        },
        getuuid:function () {
          var uuid = "";
          $.ajax({
              url:postPath+'/system/fullTextSearch/generateUuid',
              type:'post',
              async:false,
              success:function (res) {
                  uuid = res;
              }
          });
          return uuid;
        }
    };

    //保存数据
    var saveData = function(){
        $("#btn_save").click(function () {
            if(!validata()){
                return;
            }

            //保存数据
            var baseSearches=[];
            for(var i=0;i<tablelist.length;i++){
                var temp = {
                    "guid":tablelist[i].guid,
                    "serviceid":$("#guid").val(),
                    "dbKey":tablelist[i].dbkey,
                    "dtConfigId":tablelist[i].dtConfigid,
                    "fieldid":tablelist[i].fieldid,
                    "updatetype":tablelist[i].updatetype,
                    "updatefield":tablelist[i].updatefield,
                    "updatevalue":tablelist[i].updatevalue
                };
                baseSearches.push(temp);
            }
            var addtemp={
                guid:$("#guid").val(),
                servicename:$("#servicename").val(),
                indextype:"searchServer",
                remark:$("#remark").val(),
                baseSearches:baseSearches,
                pcode:$("#hid_projectid").val(),
                servicetype:$("#hid_servertype").val(),
                cronexpression:$("#cronexpression").val()
            };
            var editurl="";
            if($("#hid_operate").val() == "add"){
                editurl = postPath+'/system/fullTextSearch/addSearchInfo';
            }else if($("#hid_operate").val() == "edit") {
                editurl = postPath+'/system/fullTextSearch/updateFullsearch';
            }
            $.ajax({
                url:editurl,
                type:'post',
                data:JSON.stringify(addtemp),
                dataType:'json',
                contentType:"application/json",
                success:function (res) {
                    if(res > 0){
                        $("#guid").attr("readonly","readonly");
                        $("#hid_operate").val("edit");
                        $("#hid_serviceId").val($("#guid").val());
                        bootbox.alert("保存成功!");
                    }else{
                        bootbox.alert("保存失败,请刷新后重试!");
                    }
                }
            });
        });

        //验证数据
        var validata = function () {
            //服务ID
            if($("#guid").val() == ""){
                $("#saveError").html("服务ID不能为空!");
                return false;
            }else if(!/[a-z]/.test($("#guid").val())){
                $("#saveError").html("检索服务ID只能是小写字母!");
                return false;
            }
            else{
                if($("#hid_operate").val() == "add"){
                    var isexit = false;
                    $.ajax({
                        url:postPath+'/system/fullTextSearch/isExtServiceID',
                        type:'post',
                        data:{guid:$("#guid").val()},
                        async:false,
                        success:function (data) {
                            isexit = data;
                        }
                    });
                    if(isexit){
                        $("#saveError").html("服务ID已存在,请重新输入!");
                        return false;
                    }else{
                        $("#saveError").html("");
                    }
                }else{
                    $("#saveError").html("");
                }

            }

            //服务名称
            if($("#servicename").val() == ""){
                $("#saveError").html("服务名称不能为空!");
                return false;
            }else{
                $("#saveError").html("");
            }
            //调度周期
            if($("#cronexpression").val() == ""){
                $("#saveError").html("请设置调度周期!");
                return false;
            }else{
                $("#saveError").html("");
            }

            //检索库表
            if(tablelist.length === 0){
                $("#saveError").html("请选择检索库表!");
                return false;
            }else {
                $("#saveError").html("");
            }

            return true;

        };
    };

    //任务调度设置
    var cronexpression = function () {
      $("#btn_set").click(function () {
          $("#cron").val($("#cronexpression").val());
          $("#conModul").modal("show");
      });

      $("#btn_affirm").click(function () {
          $("#cronexpression").val($("#cron").val());
          $("#conModul").modal("hide");
      });
      $("#tasktime").click(function () {
         $("#tasktime").find("li").each(function () {
            $(this).click(function () {
               $("#cron").val($(this).attr("time"));
            });
         });
      });
    };

    return{
        init:function () {
            otherOption();
            searchTable.init();
            saveData();
            cronexpression();
        }
    }
}();

$(function () {
    //参数
    $("#hid_servertype").val(GetQueryString("servertype"));//服务类型 添加使用
    $("#hid_operate").val(GetQueryString("operate")); //操作类型
    $("#hid_serviceId").val(GetQueryString("servercode"));//服务ID  修改使用
    $("#hid_projectid").val(GetQueryString("projectid"));//工程ID 添加修改预留
    searchService.init();
});

function GetQueryString(name){
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
}
